<template>
  <div id="pay">
    <van-nav-bar
        title="待支付"
        left-text=""
        left-arrow
        @click-left="onClickLeft"
    />
    <van-row>
      <van-col style="margin-left: 25%">支付剩余时间：</van-col>
      <van-col><van-count-down millisecond :time="nowTime" format="HH:mm:ss" style="font-size: 16px;margin-top: 0.2rem"/></van-col>
    </van-row>
    <div class="address-wrap" @click="chooseAddress">
      <div class="name" >
        <span>{{ address.username }} </span>
        <span>{{ address.phone }}</span>
      </div>
      <div class="address">
        {{ address.region }}
      </div>
      <div class="address">
        {{ address.detailed_address }}
      </div>
      <van-icon class="arrow" name="arrow" />
    </div>
    <van-cell-group>
      <van-cell title="商品" :value="`共${checkedShopCount}件`"></van-cell>
      <van-card
          v-for="(goods) in checkedShopCart"
          :key="goods.id"
          :num="goods.count===undefined?1:goods.count"
          :desc="goods.name+goods.colorName+goods.sizeName"
          :price="parseInt(goods.price).toFixed(2)"
          :title="goods.title"
          :thumb=baseURL1+goods.img
      >
      </van-card>
    </van-cell-group>
    <van-cell-group style="margin-top: 0.6rem">
      <van-cell title="商品总价" :value="'￥'+parseInt(this.sumPrice).toFixed(2)"  />
      <van-cell title="运费" :value="'￥'+parseInt(this.transportPrice).toFixed(2)"  />
      <van-cell title="实付款" :value="'￥'+(parseInt(this.sumPrice) +parseInt(this.transportPrice)).toFixed(2)"   />
      <van-cell title="订单编号" :value="uuid" is-link  />
      <van-cell title="获得积分" value="2分" />
    </van-cell-group>
    <div style="display: flex;justify-content: space-around;">
      <van-button plain round type="info" @click="toPay">确认支付</van-button>
      <van-button plain round type="danger" @click="cancelOrder">取消订单</van-button>
    </div>
  </div>
</template>

<script>

import {cancelOrders, getAllOrder, getOrderAddress} from "@/api/api";
import {mapMutations} from "vuex";
import img from "@/api/api"
import {Dialog, Toast} from "vant";

export default {
  name: "PayStatus",
  created() {
    if(this.$route.query.goodsList[0].id === undefined){
      this.shopCart = this.$store.state.orderDetail.goodsList;
      this.uuid = this.$store.state.orderDetail.uuid;
    } else{
      let orderNew = {
        uuid:this.$route.query.uuid,
        status:"",
        goodsList:this.$route.query.goodsList
      };
      this.saveOrderDetail(orderNew);
      this.shopCart = this.$route.query.goodsList;
      this.uuid = this.$route.query.uuid;
    }
    getAllOrder(2).then(
        (resp)=>{
          if(resp.data.code === 2000){
             let tempOrder = resp.data.data.order;
             tempOrder.forEach((item, index) => {
               if(item.uuid === this.uuid){
                 this.createTime = item.createTime;
               }
             })
          }else{
            Toast(resp.data.message)
          }
        }
    )
    let temp1 = {};
    let temp2 = {
         username:"",
         phone:"",
         region:"",
         detailed_address:""
    };
    getOrderAddress(this.uuid).then((response) => {
      if(response.data.code === 2000){
        temp1  = response.data.data;
        console.log(temp1)
        temp2.username = this.$store.state.chosenAddress.name;
        temp2.phone = this.$store.state.chosenAddress.tel;
        temp2.region = this.$store.state.chosenAddress.address.split("\n")[0];
        temp2.detailed_address = this.$store.state.chosenAddress.address.split("\n")[1];
        this.address = this.$store.state.chosenAddress.id === ""?temp1:temp2;
      }else{
        Toast(response.data.message);
      }
    });

  },
  data(){
    return{
      time: 15  * 60 * 1000,
      address: {},
      shopCart: [],
      baseURL1:img.src,
      sumPrice:0,
      transportPrice:0,
      uuid:"",
      createTime:""
    }
  },
  methods: {
    chooseAddress() {
      this.$router.push('/confirmOrder/myAddress');
    },
    onClickLeft() {
      this.$router.go(-1);
    },
    ...mapMutations(["saveOrderDetail"]),
    toPay() {
      window.open("http://localhost:7000/check/pay-serv/alipay/pay?subject=" + this.uuid + "&traceNo=" + this.uuid + "&totalAmount=" + (parseInt(this.sumPrice) + parseInt(this.transportPrice)))
    },
    cancelOrder() {
      Dialog.confirm({
        title: '温馨提示',
        message: '确定取消该订单吗？'
      }).then(() => {
        cancelOrders(this.uuid).then(
            (resp) => {
              if (resp.data.code === 2000) {
                Toast("取消成功！")
                location.reload()
              } else {
                Toast(resp.data.message);
              }
            })
      })
    }
    },
    computed: {
      // 1. 获取选中的商品
      checkedShopCart() {
        let shopCart = [];
        Object.values(this.shopCart).forEach((goods, index) => {
          shopCart.push(goods);
          this.sumPrice += goods.price * parseInt(goods.count);
        });
        return shopCart;
      },
      // 2. 选中商品的总件数
      checkedShopCount() {
        let goodsCount = 0;
        Object.values(this.checkedShopCart).forEach((goods, index) => {
          goodsCount += parseInt(goods.count);

        })
        return goodsCount;
      },
      //3、倒计时流去时间
      sendTime() {
        let dateStr = this.createTime;
        let before = new Date(dateStr);
        let now = new Date();
        let result = now.getTime() - before.getTime();
        return result;
      },
      nowTime(){
        return this.time-this.sendTime>0?this.time-this.sendTime:0;
      }
    },
  watch:{
    nowTime(){
      if(this.nowTime === 0){
        cancelOrders(this.uuid).then(
            (resp) => {
              if (resp.data.code === 2000) {
                this.$router.push("/dashboard/mine/mineOrder")
              } else {
                Toast(resp.data.message);
              }
            })
      }
    }
  }
}
</script>

<style scoped>
#pay{
  background-color: white;
}
.address-wrap {
  margin-bottom: 20px;
  background: #fff;
  position: relative;
  font-size: 14px;
  padding: 15px;
  color: #222333;
}
.address-wrap  .name, .address {
  margin: 10px 0;
}
.arrow {
  position: absolute;
  right: 10px;
  top: 50%;
  transform: translateY(-50%);
  font-size: 20px;
}
.address-wrap::before {
  position: absolute;
  right: 0;
  bottom: 0;
  left: 0;
  height: 2px;
  background: -webkit-repeating-linear-gradient(135deg, #ff6c6c 0, #ff6c6c 20%, transparent 0, transparent 25%, #1989fa 0, #1989fa 45%, transparent 0, transparent 50%);
  background: repeating-linear-gradient(-45deg, #ff6c6c 0, #ff6c6c 20%, transparent 0, transparent 25%, #1989fa 0, #1989fa 45%, transparent 0, transparent 50%);
  background-size: 80px;
  content: '';
}
</style>
